import { createRouter, createWebHistory } from "vue-router";
import Test from "../views/Test.vue";
import Login from "../views/Login.vue";
import Home from "../views/HomePage.vue";
import DashBoard from "../views/dashboard/DashBoard.vue";
import Article from "../views/dashboard/Article.vue";
import Category from "../views/dashboard/Category.vue";

function isLoggedIn() {
    // 这里可以检查localStorage中的token，或者发送请求到服务器验证用户状态
    const token = localStorage.getItem('token');
    return token ? true : false;
}

const routes = [
    { path: "/test", component: Test, name: 'Test' },
    { path: "/", component: Home, name: 'Home' },
    { path: "/detail", component: () => import("../views/Detail.vue"), name: 'Detail' },
    { path: "/login", component: Login, name: 'Login' },
    {
        path: "/dashboard", component: DashBoard, name: 'DashBoard',
        children: [
            {
                path: 'article',
                component: Article,
            },
            {
                path: 'category',
                component: Category,
            },
        ],
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    if ((to.path === '/dashboard/*' || to.path === '/dashboard') && !isLoggedIn()) {
        // 如果用户尝试访问'/dashboard'但没有token，则重定向到'/login'
        next('/login');
    } else {
        // 否则，允许访问
        next();
    }
});

export { router, routes }